<?php

namespace app\models;

use Yii;
use app\models\Cart;
use app\models\SysBalance;
use app\models\YeDetail;
use app\models\alilib\AlipaySubmit;
use app\models\SysUsers;

/**
 * This is the model class for table "{{%order}}".
 *
 * @property integer $id
 * @property string $orderId
 * @property integer $add_time
 * @property string $goods_sumPrice
 * @property string $sale_price
 * @property string $note
 * @property integer $buy_uid
 * @property string $company_name
 * @property string $address_name
 * @property string $mobile
 * @property string $address
 * @property string $invoices
 * @property integer $status
 * @property integer $supportmetho
 * @property integer $freetype
 * @property string $freeprice
 * @property string $closemsg
 * @property string $create_user
 * @property integer $support_time
 * @property string $support_user
 * @property string $modify_user
 * @property string $sellerRemark
 * @property string $userfree
 * @property string $freecode
 * @property integer $seller_uid
 * @property string $seller_company
 * @property integer $fahuoaddress
 * @property integer $fahuo_time
 * @property string $express_user
 * @property integer $coupon
 * @property integer $score
 */
class Order extends \yii\db\ActiveRecord {

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%order}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['orderId', 'goods_sumPrice', 'buy_uid', 'company_name', 'orderInfo', 'create_user'], 'required'],
            [['add_time', 'buy_uid', 'status', 'supportmetho', 'freetype', 'support_time', 'seller_uid', 'fahuo_time', 'modify_time', 'close_time', 'finish_time', 'coupon', 'score'], 'integer'],
            [['goods_sumPrice', 'sale_price', 'freeprice'], 'number'],
            [['note', 'sellerRemark'], 'string'],
            [['orderId', 'company_name', 'seller_phone', 'create_user', 'support_user', 'modify_user', 'close_user', 'finish_user', 'userfree', 'express_user'], 'string', 'max' => 50],
            [['address_name', 'address', 'invoices', 'closemsg', 'seller_company', 'fahuoaddress', 'orderInfo'], 'string', 'max' => 255],
            [['mobile'], 'string', 'max' => 30],
            [['freecode'], 'string', 'max' => 100]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'orderId' => '订单号',
            'add_time' => '下单时间',
            'goods_sumPrice' => '商品总额',
            'orderInfo' => '订单描述',
            'sale_price' => '优惠总额',
            'note' => '备注',
            'buy_uid' => '买方ID',
            'company_name' => '公司名',
            'address_name' => '收货人',
            'mobile' => '联系手机',
            'address' => '收货地址',
            'invoices' => '发票抬头',
            'status' => '订单状态 1:待付款 2：待发货  3:待收货 4:完成 5:关闭',
            'supportmetho' => '支付方式 1:支付宝 2:微信 3：余额',
            'freetype' => '用户快递方式  1:平邮 2:快递 3:ems 0:卖家包邮',
            'freeprice' => '快递费用',
            'closemsg' => '关闭原因',
            'create_user' => '订单创建者',
            'support_time' => '支付时间',
            'support_user' => '付款者',
            'modify_user' => '订单修改者',
            'modify_time' => '订单修改时间',
            'sellerRemark' => '卖方备注',
            'userfree' => '给用户配送快递方式 0:无需快递',
            'freecode' => '快递编号',
            'seller_uid' => '卖方id',
            'seller_phone' => '卖方电话',
            'seller_company' => '卖方公司名',
            'fahuoaddress' => '发货地址',
            'fahuo_time' => '发货时间',
            'express_user' => '发货者',
            'close_user' => '关闭者',
            'close_time' => '关闭时间',
            'finish_time' => '完成时间',
            'finish_user' => '完成者',
            'coupon' => 'Coupon',
            'score' => 'Score',
        ];
    }

    public function getOrderDetail() {
        return $this->hasMany(OrderDetail::className(), ['orderId' => 'orderId', 'supId' => 'seller_uid']);
    }

    /**

     * author:sunjian
     * time:2015年12月30日15:28:54
     * params: array
     * content: 判断商品是否可买
     * return :array
     *      */
    static function checkItems($ids) {
        $ids = implode(',', $ids);
        $list = Cart::getCartListByIds($ids);
        $return = [];
        $list2 = [];
        $total = 0;
        foreach ($list as $k => $v) {
            if ($v['quantity'] > $v['goodsHy']['hysl']) {
                $return['status'] = false;
                $return['info'] = $v['goodsHy']['spm'] . "，库存不足，仅有" . $v['goodsHy']['hysl'] . "件";
                return $return;
            }
            if ($v['quantity'] < $v['goodsHy']['qdsl']) {
                $return['status'] = false;
                $return['info'] = $v['goodsHy']['spm'] . "，起订数量为" . $v['goodsHy']['qdsl'] . "件";
                return $return;
            }
            $list2[$k]['hyId'] = $v['hy_id'];
            $list2[$k]['goodsId'] = $v['goodsHy']['sp_id'];
            $list2[$k]['title'] = $v['goodsHy']['spm'];
            $list2[$k]['img'] = "";
            $list2[$k]['qym'] = $v['goodsHy']['qym'];
            $list2[$k]['xj'] = $v['goodsHy']['xj'];
            $list2[$k]['cs'] = $v['goodsHy']['cs'];
            $list2[$k]['price'] = $v['goodsHy']['hsdj'];
            $list2[$k]['quantity'] = $v['quantity'];
            $total+=$list2[$k]['price'] * $list2[$k]['quantity'];
        }
        $return['status'] = true;
        $return['list'] = $list2;
        $return['total'] = $total;
        $return['qyid'] = $list[0]['goodsHy']['qy_id'];
        $return['mjgsxx'] = $list[0]['goodsHy']['mjgsxx'];
        $return['dhhm'] = $list[0]['goodsHy']['dhhm'];
        $return['fhdz'] = $list[0]['goodsHy']['fhdz'];
        return $return;
    }

    /**

     * author:sunjian
     * time:2015年12月30日17:13:22
     * params: orderId
     * content: 删除订单和订单详情（回滚操作）
     * return :void
     *      */
    static function delOrder($orderId) {
        $order = Order::findOne($orderId);
        CouponList::deleteAll($order->coupon);
        static::deleteAll(['orderId' => $orderId]);
        OrderDetail::deleteAll(['orderId' => $orderId]);
    }

    /**

     * author:sunjian
     * time:2015年12月31日15:07:48
     * params: userid,password
     * content: 验证支付密码
     * return :bool
     *      */
    static function checkPayPassword($uid, $password) {
        $balance = SysBalance::findOne(['uid' => $uid]);
        if (md5($password) == $balance->password) {
            return true;
        } else {
            return false;
        }
    }

    /**

     * author:sunjian
     * time:2016年2月17日14:31:17
     * params: orderId,supId，pricef
     * content: 用支付宝支付订单
     * return :bool
     *      */
    static function payUseAli($price,$orderId,$supId) {
        //引入阿里配置
       header("Content-type:text/html;charset=utf-8");
       require_once(__DIR__ . '/../config/alipay.config.php');

        //支付类型
        $payment_type = "1";
        //必填，不能修改
        //服务器异步通知页面路径
        $notify_url =ALIPAY_URL. "order/alipay-notice";
        //需http://格式的完整路径，不能加?id=123这类自定义参数
        //页面跳转同步通知页面路径
        $return_url =ALIPAY_URL. "order/alipay-return";
        //需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/
        //商户订单号
        $out_trade_no = $orderId . '-' . $supId;
        //商户网站订单系统中唯一订单号，必填
        //订单名称
        $subject = '找化妆品网';
        //必填
        //付款金额
       // $total_fee = $price;
        $total_fee = 0.01;
        //必填
        //订单描述

        $body = "订单号：".$orderId;
        //商品展示地址
        $show_url = 'http://www.zhaohuazhaungpin.com';
        //需以http://开头的完整路径，例如：http://www.商户网址.com/myorder.html
        //防钓鱼时间戳
        $anti_phishing_key = "";
        //若要使用请调用类文件submit中的query_timestamp函数
        //客户端的IP地址
        $exter_invoke_ip = "";
        //非局域网的外网IP地址，如：221.0.0.1
        $parameter = array(
            "service" => "create_direct_pay_by_user",
            "partner" => trim($alipay_config['partner']),
            "seller_email" => trim($alipay_config['seller_email']),
            "payment_type" => $payment_type,
            "notify_url" => $notify_url,
            "return_url" => $return_url,
            "out_trade_no" => $out_trade_no,
            "subject" => $subject,
            "total_fee" => $total_fee,
            "body" => $body,
            "show_url" => $show_url,
            "anti_phishing_key" => $anti_phishing_key,
            "exter_invoke_ip" => $exter_invoke_ip,
            "_input_charset" => trim(strtolower($alipay_config['input_charset']))
        );
        $alipaySubmit = new AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter, "get", "确认");
        echo $html_text;
        
    }
     /**

     * author:sunjian
     * time:2016年2月18日14:28:53
     * params:alipayNo
     * content: 用支付宝完成订单
     * return :bool
     *      */
     static function alipayFinish($alipayNo,$orderId,$supId){
        $condition = "orderId='$orderId'";
        $cd['orderId'] = $orderId;
        if ($supId) {
            $condition.=" and seller_uid=" . $supId;
            $cd['seller_uid'] = $supId;
        }
        $order = static::findOne($cd);
        if($order->status!=1){
            return ;
        }
        //写日志
        if(static::writeLog($alipayNo,$orderId,$supId)){
           static::updateAll(['status' => 2, 'support_time' => time(), 'supportmetho' => 1], $condition);
        }else{
           static::updateAll(['status' =>6, 'support_time' => time(), 'supportmetho' => 1], $condition);
        }
    }
    
      /**

     * author:sunjian
     * time:2016年2月18日14:44:26
     * params:$alipayNo
     * content: 日志操作
     * return :bool
     *      */
      static function writeLog($alipayNo,$orderId,$supId) {
       $condition = "orderId='$orderId'";
        $cd['orderId'] = $orderId;
        if ($supId) {
            $condition.=" and seller_uid=" . $supId;
            $cd['seller_uid'] = $supId;
        }
        
        $order = static::findOne($cd);
        $user = SysUsers::findOne($order->buy_uid);
        $price=static::getOrderPrice($orderId, $supId);
        
        $log = new YeDetail();
        $log->uid = $user->id;
        $log->type = 3;
        $log->account = $price;
        $log->detail = "订单:".$order->orderId."-支付宝交易号：".$alipayNo;
        $log->result = '支付订单成功';
        $log->orderid = $order->id;
        $log->style = 2;
        $log->create_time = time();
        $log->operator = isset($user->truename) ? $user->truename : $user->phone;
        if ($log->save()) {
            return true;
        } else {

            return false;
        }
    }
    /**

     * author:sunjian
     * time:2016年1月8日17:47:56
     * params: orderId,supId，pricef
     * content: 用余额支付订单
     * return :bool
     *      */
    static function payUseYue($orderId, $supId, $pricef) {
        $price = static::getOrderPrice($orderId, $supId);
        if (!$price) {
            $return['status'] = false;
            $return['info'] = "订单可能已被支付或部分支付";
            return $return;
        }
        if ($price != $pricef) {
            $return['status'] = false;
            $return['info'] = "订单可能已被修改，请刷新重新尝试";
            return $return;
        }
        $yue = static::getYue();
        $return = [];
        if ($price > $yue) {
            $return['status'] = false;
            $return['info'] = "余额不足";
            return $return;
        }
        return static::payForOrderByYue($orderId, $supId, $price);
    }

    /**

     * author:sunjian
     * time:2015年12月31日15:27:30
     * params: orderId,supId,price
     * content: 更新订单状态
     * return :bool
     *      */
    static function payForOrderByYue($orderId, $supId, $price) {
        $user = Yii::$app->user->identity;
        $condition = "orderId='$orderId'";
        $cd['orderId'] = $orderId;
        if ($supId) {
            $condition.=" and seller_uid=" . $supId;
            $cd['seller_uid'] = $supId;
        }
        $return = [];
        $order = static::findOne($cd);
        if (static::updateAll(['status' => 2, 'support_time' => time(), 'supportmetho' => 3, 'support_user' => $user->truename], $condition)) {
            $detail = "订单：" . $orderId;
            if (static::yueOrder($price, $detail, $orderId, $order->id)) {
                $return['status'] = true;
                return $return;
            } else {
                static::updateAll(['status' => 1, 'support_time' => '', 'support_user' => ''], $condition);
                $return['status'] = false;
                $return['info'] = '余额操作失败';
                return $return;
            }
        } else {
            $return['status'] = false;
            $return['info'] = '订单操作失败';
            return $return;
        }
    }

    /**

     * author:sunjian
     * time:2015年12月31日15:27:30
     * params:price, detail
     * content: 余额日志操作
     * return :bool
     *      */
    static function writeYueLog($price, $detail, $orderId, $orderid) {
        $user = Yii::$app->user->identity;
        if ($user->role != 4 && $user->role != 3) {
            $parent = Users::findOne($user->parent_id);
        } else {
            $parent = $user;
        }
        $log = new YeDetail();
        $log->uid = $parent->id;
        $log->type = 3;
        $log->account = $price;
        $log->detail = $detail;
        $log->result = '支付订单成功';
        $log->orderid = $orderid;
        $log->style = 5;
        $log->create_time = time();
        $log->operator = isset($user->truename) ? $user->truename : $user->phone;
        if ($log->save()) {
            return true;
        } else {
            return false;
        }
    }

    /**

     * author:sunjian
     * time:2015年12月31日15:27:30
     * params: price,detail
     * content: 余额操作
     * return :bool
     *      */
    static function yueOrder($price, $detail, $orderId, $orderid) {
        $user = Yii::$app->user->identity;
        if ($user->role != 4 && $user->role != 3) {
            $parent = Users::findOne($user->parent_id);
        } else {
            $parent = $user;
        }
        $yue = SysBalance::find()->where('uid=' . $parent->id)->one();
        $old = $yue->account_ye;
        $yue->account_ye = $old - $price;
        if ($yue->save()) {
            if (static::writeYueLog($price, $detail, $orderId, $orderid)) {
                return true;
            } else {
                //回滚
                $yue->account_ye = $old;
                if ($yue->save()) {
                    return false;
                }
            }
        } else {

            return false;
        }
    }

    /**

     * author:sunjian
     * time:2015年12月31日15:27:30
     * params: orderId,supId
     * content: 获取订单总价
     * return :bool or float
     *      */
    static function getOrderPrice($orderId, $supId) {
        $condition = "orderId='$orderId'";
        if ($supId) {
            $condition.=" and seller_uid=" . $supId;
        }
        $orderList = Order::find()->andWhere($condition)->asArray()->all();
        $sum = 0;
        foreach ($orderList as $v) {
            if ($v['status'] == 1) {
                $sum+=$v['goods_sumPrice'] - $v['sale_price'];
            } else {
                return false;
            }
        }
        return $sum;
    }

    /**

     * author:sunjian
     * time:2015年12月31日15:27:30
     * content: 获取余额
     * return :bool
     *      */
    static function getYue() {
        $user = Yii::$app->user->identity;
        if ($user->role != 4 && $user->role != 3) {
            $parent = Users::findOne($user->parent_id);
        } else {
            $parent = $user;
        }
        $yue = SysBalance::find()->andWhere("uid=$parent->id")->asArray()->one();
        return $yue['account_ye'];
    }

    /**

     * author:sunjian
     * time:2016年1月3日20:20:19
     * content: 归还库存
     * return :bool
     *      */
    static function backHysl($orderId, $supId) {
        $orderDetail = OrderDetail::find()->andWhere(['orderId' => $orderId, 'supId' => $supId])->asArray()->all();
        $flag = true;
        foreach ($orderDetail as $v) {
            $hy = BaseGoodsHy::findOne($v['hyId']);
            $hy->hysl+=$v['quantity'];
            if ($hy->save()) {
                
            } else {
                $flag = false;
            }
        }
        return $flag;
    }

    /**

     * author:sunjian
     * time:2016年1月9日14:47:44
     * content: 确认收货
     * return :bool
     *      */
    public function finish() {
        if ($this->save()) {
            if ($this->receive()) {
                return true;
            } else {
                $this->attributes = $this->oldAttributes;
                $this->save();
                return false;
            }
        } else {
            return false;
        }
    }

    /**

     * author:sunjian
     * time:2016年1月9日14:47:44
     * content: 货款打给卖家
     * return :bool
     *      */
    public function receive() {
        $uid = $this->seller_uid;
        $log = new YeDetail();
        $log->uid = $uid;
        $log->type = 5;
        if ($this->supportmetho == 3) {
            $log->style = 1;
        } elseif ($this->supportmetho == 1) {
            $log->style = 2;
        } elseif ($this->supportmetho == 2) {
            $log->style = 3;
        }

        $log->account = '+' . ($this->goods_sumPrice - $this->sale_price) * 1;
        $log->detail = "订单：" . $this->orderId;
        $log->orderid = $this->id;
        $log->result = '订单完成';
        $log->create_time = time();
        $log->operator = "系统";
        if ($log->save()) {
            $balance = SysBalance::findOne(['uid' => $uid]);
            $balance->account_ye = $balance->account_ye + ($this->goods_sumPrice - $this->sale_price) * 1;
            if ($balance->save()) {
                return true;
            } else {
                $log->delete();
                return false;
            }
        } else {
            return false;
        }
    }

    /**

     * author:sunjian
     * time:2016年1月17日16:23:38
     * content: 系统取消订单
     * return :bool
     *      */
    public function closeOrder() {
        $time = time() - 3600 * 24;
        $data = $this->find()->where('status=1 and add_time<' . $time)->asArray()->all();

        foreach ($data as $v) {
            $order = $this->findOne($v['id']);
            $order->status = 5;
            $order->closemsg = '系统关闭';
            $order->close_user = '系统';
            $order->close_time=time();
            if ($order->save()) {
                if ($this->backHysl($v['orderId'], $v['seller_uid'])) {
                    
                } else {
                    $order->attributes = $order->oldAttributes;
                    $order->save();
                }
            }
        }
    }

    /**

     * author:sunjian
     * time:2016年1月17日18:15:48
     * content: 系统完成订单
     * return :bool
     *      */
    public function finishOrder() {
        $time = time() - 3600 * 24 * 30;
        $data = $this->find()->where('status=3 and fahuo_time<' . $time)->asArray()->all();

        foreach ($data as $v) {
            $order = $this->findOne($v['id']);
            $order->status = 4;
            $order->finish_user = '系统';
            $order->finish_time = time();
            if ($order->save()) {
                $uid = $v['seller_uid'];
                $log = new YeDetail();
                $log->uid = $uid;
                $log->type = 5;
                $log->account = '+' . ($v['goods_sumPrice'] - $v['sale_price']) * 1;
                $log->detail = "订单：" . $v['orderId'];
                $log->orderid = $v['id'];
                $log->result = '订单完成';
                $log->create_time = time();
                $log->operator = "系统";
                if ($log->save()) {
                    $balance = SysBalance::findOne(['uid' => $uid]);
                    $balance->account_ye = $balance->account_ye + ($v['goods_sumPrice'] - $v['sale_price']) * 1;
                    if ($balance->save()) {
                        echo 1;
                    } else {
                        $log->delete();
                        $order->attributes = $order->oldAttributes;
                        $order->save();
                    }
                } else {
                    $order->attributes = $order->oldAttributes;
                    $order->save();
                }
            } else {
                
            }
        }
    }

}
